﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using C1.Phone.RichTextBox;
using C1.Phone;
using C1.Phone.RichTextBox.Documents;

namespace ControlExplorer.Controls.RichTextBox
{
    public partial class HyperlinkPopup : UserControl
    {
        private C1RichTextBox _richTextBox;
        private C1Popup _popup;

        public HyperlinkPopup(C1RichTextBox rtb)
        {
            InitializeComponent();

            // init C1Popup
            _popup = new C1Popup();
            _popup.Content = this;

            // set local reference to C1RichTextBox
            _richTextBox = rtb;
        }

        public void ShowPopup()
        {
            // set url text
            txtText.Text = _richTextBox.Selection.Text;
            
            // set url if opening existing hyperlink
            if (_richTextBox.Selection.Html.Contains("<a") && _richTextBox.Selection.Html.Contains("href"))
            {
                // parse out the href part
                int i = _richTextBox.Selection.Html.IndexOf("href");
                string j = _richTextBox.Selection.Html.Substring(i);
                int k = j.IndexOf('"');
                string l = j.Substring(k + 1);

                txtUrl.Text = l.Substring(0, l.IndexOf('"'));
            }
            else
            {
                txtUrl.Text = "http://";
            }

            // open C1Popup
            _popup.IsOpen = true;
        }

        public void ClosePopup()
        {
            // close C1Popup
            _popup.IsOpen = false;

            // set focus back to the richtextbox
            _richTextBox.Focus();
        }

        private void btnOK_Click(object sender, RoutedEventArgs e)
        {
            Uri url = null;
            try
            {
                url = new Uri(txtUrl.Text, UriKind.Absolute);
            }
            catch (UriFormatException)
            {
                if (txtUrl.Text.Trim().Equals("http://", StringComparison.OrdinalIgnoreCase))
                {
                    this.ClosePopup();
                    return;
                }

                try
                {
                    url = new Uri("http://" + txtUrl.Text, UriKind.Absolute);
                }
                catch (UriFormatException)
                {
                    MessageBox.Show("Invalid url");
                }
            }

            using (new DocumentHistoryGroup(_richTextBox.DocumentHistory))
            {
                if (_richTextBox.Selection.Text != txtText.Text)
                {
                    _richTextBox.Selection.Delete();
                    var run = new C1Run { Text = txtText.Text };
                    _richTextBox.Selection.Start.InsertInline(run);
                    run.ContentRange.MakeHyperlink(url);
                    _richTextBox.Selection = run.ContentRange;
                }
                else
                {
                    _richTextBox.Selection.MakeHyperlink(url);
                }
            }
            this.ClosePopup();
        }

        private void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            this.ClosePopup();
        }

        private void btnRemove_Click(object sender, RoutedEventArgs e)
        {
            using (new DocumentHistoryGroup(_richTextBox.DocumentHistory))
            {
                var range = _richTextBox.Selection;
                range.TrimRuns();
                _richTextBox.Selection = range;

                foreach (var r in range.EditRanges)
                {
                    r.RemoveHyperlinks();
                }
            }
            this.ClosePopup();
        }

        private void txtUrl_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (txtUrl.Text.Length > 0)
            {
                btnOK.ClearValue(Button.BorderBrushProperty);
                btnOK.ClearValue(Button.BackgroundProperty);
                btnOK.ClearValue(Button.ForegroundProperty);
                btnOK.IsEnabled = true;
            }
            else
            {
                btnOK.IsEnabled = false;
                btnOK.Dispatcher.BeginInvoke(() =>
                    {
                        btnOK.BorderBrush = btnCancel.BorderBrush;
                        btnOK.Background = btnCancel.Background;
                        btnOK.Foreground = new SolidColorBrush(Colors.Gray);
                    });
            }
        }
    }
}
